package com.jinxin.platform.cdzxkacs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdzxkacs.bean.CdzxkacsDevice;
import com.jinxin.platform.cdzxkacs.bean.CdzxkacsUser;
import com.jinxin.platform.cdzxkacs.bean.CdzxkacsUserTemplate;
import com.jinxin.platform.cdzxkacs.bean.bo.UserInfo;
import com.jinxin.platform.cdzxkacs.common.Constant;
import com.jinxin.platform.cdzxkacs.common.SysUserVO;
import com.jinxin.platform.cdzxkacs.mapper.CdzxkacsDeviceMapper;
import com.jinxin.platform.cdzxkacs.mapper.CdzxkacsUserMapper;
import com.jinxin.platform.cdzxkacs.mapper.CdzxkacsUserTemplateMapper;
import com.jinxin.platform.cdzxkacs.rpc.SysUserRpc;
import com.jinxin.platform.cdzxkacs.service.IAcsUserService;
import com.jinxin.platform.cdzxkacs.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-01-29
 * @Author: Lingnan
 **/
@Service
public class AcsUserServiceImpl implements IAcsUserService {
    @Autowired
    private CdzxkacsUserMapper userMapper;
    @Autowired
    private CdzxkacsUserTemplateMapper userTemplateMapper;
    @Autowired
    private SysUserRpc sysUserRpc;
    @Autowired
    private CdzxkacsDeviceMapper deviceMapper;

    @Override
    public List<CdzxkacsUser> list(HashMap param) {
        return userMapper.list(param);
    }

    @Override
    public List<CdzxkacsUser> listPage(HashMap param) {
        return userMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return userMapper.listPageCount(param);
    }

    @Override
    public JsonResult listDeviceNames(String communityId) {
        if(StringUtils.isEmpty(communityId)){
            return JsonResult.error("小区不存在");
        }
        List<Map<String, Object>> mapList = userMapper.listDeviceNames(communityId);
        return JsonResult.ok(mapList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult delete(String id,String deviceId,Integer type) {
        if(StringUtils.isEmpty(id) || StringUtils.isEmpty(deviceId) || StringUtils.isEmpty(type)){
            return JsonResult.error("参数异常");
        }
        CdzxkacsDevice device = deviceMapper.selectByKey(deviceId);
        if(device == null){
            return JsonResult.error("设备不存在");
        }
        String persionLibraryId = getpLibraryIdByType(type);
        JsonResult jsonResult = sysUserRpc.personDelete(persionLibraryId, device.getSerialNum(), device.getProductCode(), id);
        if(jsonResult != null && jsonResult.getSuccess()){
            int result = userMapper.deleteByKey(id);
            if(result > 0){
                userTemplateMapper.deleteByUserId(id);
                return JsonResult.ok("删除成功","");
            }
        }
        return JsonResult.error("删除失败");
    }

    private String getpLibraryIdByType(int type){
        return type == Constant.USER_TYPE_EMPLOYEE ? Constant.PERSION_LIBRARYID_3 : Constant.PERSION_LIBRARYID_4;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveOrUpdate(CdzxkacsUser record) {
        if (record == null){
            return JsonResult.error("参数错误，操作失败");
        }
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if (currentUser == null){
            return JsonResult.error("获取当前用户失败");
        }
        String id = record.getId();
        boolean idIsNull = StringUtils.isEmpty(id);
        String nameId = record.getNameId();
        // 如果是批量下发的需要查询是否已经下发过，避免重复下发导致数据错误
        if(record.isBatch() && idIsNull && !StringUtils.isEmpty(nameId)){
            HashMap param = new HashMap();
            param.put("phone",record.getPhone());
            param.put("communityId",record.getCommunityId());
            param.put("blockId",record.getBlockId());
            param.put("deviceId",record.getDeviceId());
            param.put("nameId",nameId);
            CdzxkacsUser cdzxkacsUser = userMapper.selectOne(param);
            if(cdzxkacsUser != null){
                return JsonResult.error("用户("+record.getName()+")已被下发");
            }
        }
        int count;
        String msg;
        String templateArrStr = record.getTimeTemplate();
        JSONArray templateArr = JSONArray.parseArray(templateArrStr);
        Integer personType = record.getPersonType();
        String persionLibraryId = getpLibraryIdByType(personType);
        CdzxkacsDevice device = deviceMapper.selectByKey(record.getDeviceId());
        if(device != null){
            JsonResult jsonResult = sysUserRpc.personCreateOrUpdate(persionLibraryId, device.getSerialNum(), device.getProductCode(), record);
            if(jsonResult != null && jsonResult.getSuccess()){
                if(idIsNull){
                    // 手机号不重复
//                    String phone = record.getPhone();
//                    if(!StringUtils.isEmpty(phone) && !StringUtils.isEmpty(personType)){
//                        HashMap param = new HashMap();
//                        param.put("phone", phone);
//                        param.put("personType", personType);
//                        CdzxkacsUser cdzxkacsUser = userMapper.selectOne(param);
//                        if(cdzxkacsUser != null){
//                            return JsonResult.error("手机号已存在");
//                        }
//                    }
                    //{"code":"0","r1":"{\"Response\": {\t\"ResponseURL\": \"/LAPI/V1.0/PeopleLibraries/3/People\",\t\"CreatedID\": -1, \t\"ResponseCode\": 1, \t\"SubResponseCode\": 0, \t\"ResponseString\": \"Common Error\",\t\"StatusCode\": 10,\t\"StatusString\": \"SRLZ Fail\",\t\"Data\": \"null\"\t}}"}
                    String jstr = jsonResult.getData().toString();

                    String personID = "",faceID = "";
                    if(!StringUtils.isEmpty(jstr)){
                        String dataStr = CommonUtil.getDataFromResult(jstr);
                        JSONObject dataJson = JSONObject.parseObject(dataStr);
                        JSONArray personList = dataJson.getJSONArray("PersonList");
                        JSONObject personD = personList.getJSONObject(0);
                        personID = personD.getString("PersonID");
                        JSONArray faceList = personD.getJSONArray("FaceList");
                        JSONObject faceD = faceList.getJSONObject(0);
                        faceID = faceD.getString("FaceID");
                    }
                    if(StringUtils.isEmpty(personID)){
                        return JsonResult.error("接口返回参数异常");
                    }
                    record.setId(personID);
                    record.setFaceId(faceID);
                    record.setCreateTime(LocalDateTime.now());
                    record.setCreateUserId(currentUser.getUserId());
                    record.setCreateUserName(currentUser.getUserAccount());
                    count = userMapper.insert(record);
                    if(templateArr != null && templateArr.size() > 0){
                        for (int i = 0; i < templateArr.size(); i++) {
                            JSONObject obj = templateArr.getJSONObject(i);
                            CdzxkacsUserTemplate userTemplate = new CdzxkacsUserTemplate();
                            userTemplate.setUserId(record.getId());
                            userTemplate.setTimeTemplateId(obj.getString("id"));
                            userTemplate.setTimeTemplateName(obj.getString("name"));
                            userTemplateMapper.insert(userTemplate);
                        }
                    }
                    msg = "新增成功";
                }else {
                    count = userMapper.updateByKey(record);
                    userTemplateMapper.deleteByUserId(id);
                    if(templateArr != null && templateArr.size() > 0){
                        for (int i = 0; i < templateArr.size(); i++) {
                            JSONObject obj = templateArr.getJSONObject(i);
                            CdzxkacsUserTemplate userTemplate = new CdzxkacsUserTemplate();
                            userTemplate.setUserId(record.getId());
                            userTemplate.setTimeTemplateId(obj.getString("id"));
                            userTemplate.setTimeTemplateName(obj.getString("name"));
                            userTemplateMapper.insert(userTemplate);
                        }
                    }
                    msg = "更新成功";
                }
                if(count > 0){
                    return JsonResult.ok(msg,"");
                }else {
                    return JsonResult.error("操作失败，请重试");
                }
            }else {
                String errMsg = jsonResult != null ? jsonResult.getMsg() : "操作失败，请重试";
                return JsonResult.error(errMsg);
            }
        }else {
            return JsonResult.error("获取设备信息失败，请重试");
        }
    }

    @Override
    public JsonResult listUserRecord() {
        List<UserInfo> userInfos = userMapper.listUserRecord();
        return JsonResult.ok(userInfos);
    }

    @Override
    public JsonResult getTemplatesByUserId(String id) {
        if(StringUtils.isEmpty(id)){
            return JsonResult.error("用户id不存在");
        }
        HashMap param = new HashMap();
        param.put("userId",id);
        List<CdzxkacsUserTemplate> list = userTemplateMapper.list(param);
        return JsonResult.ok(list);
    }
}
